<script setup lang='ts' name="rights-management">
import type { VNode, VNodeProps } from 'vue'

import { delOrgRoles, dispatchOrgRole, getCompanyOrg, getOrgRoles, getPrivileges, updateOrgRoles, userAuthInfo } from '@fl/api/iam-api'
import { ElButton, ElCard, ElCheckbox, ElDialog, ElInput, ElTransfer, ElTree } from 'element-plus'
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'

import roleCheckbox from '../role-authority/component/role-checkbox/index.vue'

const roleCheckboxRef = ref<any>(null)
const treeRoleList = ref<any>([])
const authList = ref<any>([])
const role_id = ref<any>()
const roleInformation = ref<any>()

const dialogDistributionUserVisible = ref(false)
const assignRolesList = ref<any>([])
const resultList = ref<any>([])
const router = useRouter()
const defaultChecked = ref<any>([])
const alreadyHaveAuth = ref<any>([])

const rightValue = ref([1])
function handleNodeClick(data: any) {
    console.log('handleNodeClick', data)

    role_id.value = data.id
    treeRoleList.value.forEach((item: any) => {
        if (item.id === role_id.value) {
            roleInformation.value = item
            alreadyHaveAuth.value = item.privileges
        }
    })

    roleCheckboxRef.value.getAlreadyHaveAuth(alreadyHaveAuth.value)
}

function getUserAuthList() {
    getCompanyOrg({ page: 1, size: 9999 }).then((res: any) => {
        const target = res.map((v: any) => {
            return {
                key: v.objectID,
                label: v.qiymc,
            }
        })
        transferData.value = target
    })
}

const defaultProps = {
    children: 'children',
    label: 'label',
}

const dataTree = ref<any>([
    {
        children: [
            // {
            //     label: '所有员工',
            // },
        ],
        id: 'root',
        label: '所有角色',
    },
])

const filterText = ref('')
const checkedAllPage = ref(false)

const isIndeterminate = ref(false)

const treeRef = ref<InstanceType<typeof ElTree>>()

function createSection() {
    router.push('/admin/org-role/add-org-role')
}
function filterNode(value: string, data: any) {
    if (!value)
        return true
    return data.label.includes(value)
}

function handleCheckAll(val: boolean) {
    console.log(val, 'handleCheckAll')
    if (val)
        roleCheckboxRef.value.handleCheckAll(true)

    else
        roleCheckboxRef.value.handleCheckAll(false)
}
function distributionAuth() {
    if (!roleInformation.value?.description || !roleInformation.value?.display_name) {
        ElMessage({
            message: '请选择角色',
            type: 'warning',
        })
        return
    }
    const privileges = roleCheckboxRef.value.getCheckedCities

    updateOrgRoles({
        description: roleInformation.value.description,
        display_name: roleInformation.value.display_name,
        id: role_id.value,
        privileges,
    }, role_id.value).then((res) => {
        console.log(res, 'distributionAuth')
    })
}
function renderFunc(h: (type: string, props: VNodeProps | null, children?: string) => VNode, option: any) {
    return h('span', null, option.label)
}
const transferData = ref<any>()

function handleChangeTransfer(value: number[] | string[], direction: 'left' | 'right', movedKeys: number[] | string[]) {
    console.log(value, direction, movedKeys, 'handleChangeTransfer')
    assignRolesList.value = value
}

watch(filterText, (val) => {
    treeRef.value!.filter(val)
})

function assignRolesConfirm() {
    dispatchOrgRole({
        org_ids: assignRolesList.value,
        role_ids: [role_id.value],
    }).then((res) => {
        console.log(res, 'assignRolesConfirm')
        dialogDistributionUserVisible.value = false
    }).catch(() => {
        ElMessage({
            message: '操作失败',
            type: 'info',
        })
    })
}

async function getDataTree() {
    dataTree.value[0].children = []
    getOrgRoles({ page: 1, page_size: 9999 }).then((res: any) => {
        treeRoleList.value = res?.items
        let tempObj = {}
        res.items.forEach((item) => {
            tempObj = {
                id: item.id,
                label: item.display_name,
            }
            dataTree.value[0].children?.push(tempObj)
        })
    })
}

async function getRIndexPrivileges(org_id: string) {
    getPrivileges({
        org_id,
        page: 1,
        page_size: 9999,
    }).then((res: any) => {
        authList.value = res.items
        resultList.value = Object.values(authList.value.reduce((acc, cur) => {
            const { module_name, ...rest } = cur
            if (acc[module_name])
                acc[module_name].children.push(rest)
            else
                acc[module_name] = { children: [rest], module_name }

            return acc
        }, {}))
    })
}

function removeTree(node: any, data: any) {
    console.log(node)

    ElMessageBox.confirm(
        '该操作将永久删除，是否继续?',
        '提示',
        {
            type: 'warning',
        },
    )
        .then(() => {
            delOrgRoles(data.id).then(() => {
                getDataTree()
            })
        })
        .catch(() => {
            ElMessage({
                message: '删除失败',
                type: 'info',
            })
        })
}
function distributionUser(node: Node, data: any) {
    console.log(node, data, 'distributionUser')
    dialogDistributionUserVisible.value = true
}

function init() {
    userAuthInfo().then((res) => {
        // 暂存 新增使用
        window.sessionStorage.setItem('ORG_ID', res.org_id)

        getRIndexPrivileges(res.org_id)
        getUserAuthList()
        getDataTree()
    })
}
init()
</script>

<template>
    <div flex>
        <ElCard style="width:20%;height: 100vh;"
                mr-20
        >
            <div flex>
                <ElInput v-model="filterText" />

                <ElButton ml-6
                          class="el-button el-button--primary el-button--default"
                          @click="createSection"
                >
                    新增角色
                </ElButton>
            </div>

            <ElTree ref="treeRef"
                    class="role-tree"
                    :data="dataTree"
                    :props="defaultProps"
                    node-key="id"
                    :default-expanded-keys="['root']"
                    :default-checked-keys="defaultChecked"
                    :filter-node-method="filterNode"
                    @node-click="handleNodeClick"
            >
                <template #default="{ node, data }">
                    <span class="custom-tree-node">
                        <span>{{ node.label }}</span>

                        <span v-if="node.label !== '所有角色'">
                            <Edit style="width: 1em; height: 1em; margin-left: 12px"
                                  @click="distributionUser(node, data)"
                            />

                            <Delete style="width: 1em; height: 1em; margin-left: 18px"
                                    @click="removeTree(node, data)"
                            />

                        </span>
                    </span>
                </template>
            </ElTree>
        </ElCard>

        <ElCard style="width:80%">
            <div style="align-items: center;"
                 mb-20
                 flex
                 justify-between
            >
                <span>设置[企业管理员]对应的应用功能权限</span>

                <div flex
                     style="align-items: center;"
                >
                    <ElCheckbox v-model="checkedAllPage"
                                label="全选"
                                :indeterminate="isIndeterminate"
                                @change="handleCheckAll"
                    />

                    <ElButton class="el-button el-button--primary el-button--default"
                              ml-20
                              @click="distributionAuth"
                    >
                        保存
                    </ElButton>
                </div>
            </div>

            <roleCheckbox v-if="resultList.length !== 0"
                          ref="roleCheckboxRef"
                          :result-list="resultList"
                          :already-have-auth="alreadyHaveAuth"
            />
        </ElCard>

        <ElDialog v-model="dialogDistributionUserVisible"
                  title="全部成员"
                  width="800"
        >
            <ElTransfer v-model="rightValue"
                        style="text-align: left; display: inline-block"
                        filterable
                        :left-default-checked="[2, 3]"
                        :right-default-checked="[1]"
                        :render-content="renderFunc"
                        :titles="['所有企业', '已选择企业']"
                        :button-texts="['', '']"
                        :format="{
                            noChecked: '${total}',
                            hasChecked: '${checked}/${total}',
                        }"
                        :data="transferData"
                        @change="handleChangeTransfer"
            />

            <template #footer>
                <div class="dialog-footer">
                    <ElButton @click="dialogDistributionUserVisible = false">
                        取消
                    </ElButton>

                    <ElButton type="primary"
                              @click="assignRolesConfirm"
                    >
                        确认
                    </ElButton>
                </div>
            </template>
        </ElDialog>
    </div>
</template>

<style lang="less">
.role-tree {
    max-width: 600px;
}
</style>
